<template>
  <div class="device-management">
    <!-- 设备表格 -->
    <el-table :data="state.devices" style="width: 100%">
      <el-table-column prop="code" label="设备ID" width="120" />
      <el-table-column prop="name" label="设备名称" width="200" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          {{ row.type === "pd" ? "功率设备" : "集成设备" }}
        </template>
      </el-table-column>
      <el-table-column label="位置">
        <template #default="{ row }"> {{ row.lng }},{{ row.lat }} </template>
      </el-table-column>
      <el-table-column label="关联用户">
        <template #default="{ row }">
          <el-tag v-for="user in row.users" :key="user.id">
            {{ user.nickname }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="editDevice(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="showUserSelection(row)"
            >设备用户</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑设备对话框 -->
    <el-dialog v-model="state.dialogVisible" title="编辑设备">
      <el-form :model="state.editingDevice" label-width="80px" :rules="rules">
        <el-form-item label="设备编号">
          <el-input
            v-model="state.editingDevice.code"
            :disabled="state.editingDevice.id"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="state.editingDevice.name"
            :disabled="state.editingDevice.id"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="state.editingDevice.type"
            :disabled="state.editingDevice.id"
          >
            <el-option label="功率设备" value="pd" />
            <el-option label="集成设备" value="ic" />
          </el-select>
        </el-form-item>

        <el-form-item label="经度">
          <el-input v-model="state.editingDevice.lng" />
        </el-form-item>
        <el-form-item label="维度">
          <el-input v-model="state.editingDevice.lat" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEditedDevice">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog
      v-model="state.userSelectionVisible"
      :title="` ${state.selectedDeviceForUser.name} 用户`"
    >
      <DeviceUser
        :deviceId="state.selectedDeviceForUser.id"
        @flushDeviceList="getdevicelists({})"
        @closeDialog="state.userSelectionVisible = false"
      ></DeviceUser>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { getAllUser } from "@/api/system/user.js";
import { devicelist, updateDeviceById } from "@/api/system/device.js";
import { saveManyDeviceUsers } from "@/api/system/deviceuser.js";
import DeviceUser from "@/views/device/deviceUser.vue";
import { ElMessage } from "element-plus";
// 定义验证规则
const rules = {
  lng: [
    { required: true, message: "请输入经度", trigger: "blur" },
    {
      pattern: /^[-+]?([1-9]?\d(\.\d+)?|1[0-7]\d(\.\d+)?|180(\.0+)?)$/,
      message: "请输入有效的经度（-180 到 180 之间）",
      trigger: "blur",
    },
  ],
  lat: [
    { required: true, message: "请输入纬度", trigger: "blur" },
    {
      pattern: /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)$/,
      message: "请输入有效的纬度（-90 到 90 之间）",
      trigger: "blur",
    },
  ],
};
// 合并响应式数据
const state = reactive({
  devices: [],
  dialogVisible: false,
  userSelectionVisible: false,
  editingDevice: {},
  selectedDeviceForUser: {},
  loading: false,
});

// 显示用户选择对话框
const showUserSelection = (device) => {
  state.selectedDeviceForUser = device;
  state.userSelectionVisible = true;
};

const getdevicelists = (data) => {
  return devicelist(data).then((response) => {
    state.devices = response || [];
  });
};

// 编辑设备方法
const editDevice = (device) => {
  state.editingDevice = JSON.parse(JSON.stringify(device));
  state.dialogVisible = true;
};

// 保存编辑后的设备
const saveEditedDevice = async () => {
  try {
    state.loading = true;
    await updateDeviceById(state.editingDevice.id, state.editingDevice);
    await getdevicelists({});
    ElMessage.success("设备编辑成功");
  } catch (error) {
    console.error("设备编辑失败:", error);
    ElMessage.error("设备编辑失败，请稍后重试");
  } finally {
    state.loading = false;
    state.dialogVisible = false;
  }
};

// 初始化获取数据
getdevicelists({});
</script>

<style scoped>
/* 整体容器样式 */
.device-management {
  padding: 10px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  min-height: 100vh;
}

/* 标题样式 */
.device-management h2 {
  color: #2c3e50;
  font-size: 1.75rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.el-table {
  margin-bottom: 1.5rem;
  background-color: #fff;
  border-radius: 0.5rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
  padding: 0.75rem;
}

.el-table td {
  padding: 0.75rem;
}

.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f0f2f5;
  transition: background-color 0.3s ease;
}

/* 标签样式 */
.el-tag {
  margin-right: 0.5rem;
  margin-top: 0.5rem;
  transition: all 0.3s ease;
  border-radius: 0.25rem;
  padding: 0 0.5rem;
  height: 1.75rem;
  line-height: 1.75rem;
}

.el-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

.el-tag--close:hover {
  background-color: #f56c6c;
  color: #fff;
}

/* 按钮样式 */
.el-button {
  transition: all 0.3s ease;
  border-radius: 0.25rem;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

/* 对话框样式 */
.el-dialog {
  border-radius: 0.5rem;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.el-dialog__header {
  background-color: #f8f9fa;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__title {
  color: #2c3e50;
  font-size: 1.125rem;
  font-weight: 600;
}

.el-dialog__body {
  padding: 1.5rem;
}

.el-dialog__footer {
  padding: 0.75rem 1.5rem 1rem;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

/* 穿梭框样式 */
.el-transfer {
  display: flex;
  justify-content: center;
  margin: 1.5rem 0;
}

.el-transfer-panel {
  border-radius: 0.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.el-transfer-panel__header {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
  padding: 0.75rem;
}

.el-transfer-panel__list {
  min-height: 12.5rem;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 1rem;
}

.el-form-item__label {
  color: #606266;
  font-weight: 500;
}

.el-input {
  border-radius: 0.25rem;
  transition: border-color 0.3s ease;
}

.el-input:hover {
  border-color: #c0c4cc;
}

.el-input:focus {
  border-color: #409eff;
}
</style>
